package org.lonetree.tc.webapp.actions;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.lonetree.tc.core.User;
import org.lonetree.tc.core.User.Username;
import org.lonetree.tc.core.dao.DAOFactory;
import org.lonetree.tc.core.dao.UserDAO;
import org.lonetree.tc.core.exception.NoSuchItemException;
import org.lonetree.tc.core.id.ValidatedIdentifier.ValidationException;

public class LogonAction extends Action {

	public static final String LOGGED_IN_USER_IN_SESSION  = "logged_in_user_in_session";
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		org.apache.struts.validator.DynaValidatorForm lf = (org.apache.struts.validator.DynaValidatorForm)form;
		String username = (String)lf.get("username");
		String password = (String)lf.get("password");
		
		if(username==null||password==null||username.trim().equals("")||password.trim().equals("")){
			return mapping.findForward("failure");
		}
		
		User u = checkCredentials(username, password);
		
		if(u!=null){
			HttpSession sess = request.getSession();
			sess.setAttribute(LOGGED_IN_USER_IN_SESSION, u);
			sess.setAttribute(SecureAction.LAST_REQUEST_TIME_IN_SESSION, new Date());
			
			if(u.isAdmin())
				return mapping.findForward("success_admin");
			else
				return mapping.findForward("success_user");
		}
		else{
			return mapping.findForward("failure");
		}
	}

	private User checkCredentials(String username, String password)throws ValidationException {
		DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.FactoryImplementation.DB_DAO_FACTORY);
		UserDAO udao = factory.getUserDAO();
		try {
			User u = udao.getUser(new Username(username));
			if(u!=null && u.getPassword().equals(password) && !u.isSuspended())
			{
				return u;
			}
			else
				return null;
		} catch (NoSuchItemException e) {
			return null;
		} 
		
	}
	
}
